package com.xls.dormitoryservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xls.base.exception.BusinessException;
import com.xls.base.model.Student;
import com.xls.base.mapper.StudentMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xls.base.vo.StudentVo;
import com.xls.dormitoryservice.service.StudentService;
import com.xls.dormitoryservice.vo.StudentQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xls
 * @since 2021-03-23
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public boolean saveStudent(Student student) {
        validateStudent(student);
        return this.save(student);
    }

    @Override
    public boolean updateStudent(Student student) {
        validateStudent(student);
        return this.updateById(student);
    }

    private void validateStudent(Student student) {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("sno", student.getSno());
        if (student.getId() != null) {
            studentQueryWrapper.ne("id", student.getId());
        }
        int count = this.count(studentQueryWrapper);
        if (count > 0) {
            throw new BusinessException(6666, "已存在相同学号的学生");
        }
    }

    @Override
    public Page<StudentVo> getStudentPage(Integer page, Integer limit, StudentQuery studentQuery) {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        String sno = studentQuery.getSno();
        String name = studentQuery.getName();
        String gender = studentQuery.getGender();
        String phone = studentQuery.getPhone();
        String department = studentQuery.getDepartment();
        String major = studentQuery.getMajor();
        studentQueryWrapper
                .likeRight(!StringUtils.isEmpty(sno), "sno", sno)
                .likeRight(!StringUtils.isEmpty(name), "name", name)
                .eq(!StringUtils.isEmpty(gender), "gender", gender)
                .likeRight(!StringUtils.isEmpty(phone), "phone", phone)
                .eq(!StringUtils.isEmpty(department), "department", department)
                .eq(!StringUtils.isEmpty(major), "major", major)
                .eq("is_deleted", 0);
        return studentMapper.getStudentPage(new Page<>(page, limit), studentQueryWrapper);
    }
}
